define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue', 'axios'], function ($, undefined, Backend, Table, Form, Vue, axios) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'book.words/index' + location.search,
                    // add_url: 'book.words/add',
                    edit_url: 'book.words/edit',
                    // del_url: 'book.words/del',
                    multi_url: 'book.words/multi',
                    import_url: 'book.words/import',
	                dragsort_url: '',
                    table: 'book_words',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
	            sortOrder: 'asc',
                fixedColumns: true,
                fixedRightNumber: 1,
	            pageSize: 50,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'book_id', title: __('Book_id'), searchList: Config.book_list, formatter: (value,row,index)=>{return row.book.title}},
                        {field: 'unit_id', title: __('Unit_id'), searchList: Config.unit_list, formatter: (value,row,index)=>{return row.unit_text}},
                        {field: 'word', title: __('Word'), operate: 'LIKE'},
                        {field: 'ipa', title: __('Ipa'), operate: false},
                        {field: 'chinese', title: __('Chinese'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'weigh', title: __('Weigh'), operate: false},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"hidden":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

			$('[name=book_id]').on('change',function(){
				let book_id = $(this).val();
				var options = '<option value="">选择</option>';
				$.get('book/unit', {book_id:book_id}, function(data){
					$.each(data, function (key, value) {
						options += '<option value="' + key + '">' + value + '</option>';
					})
					$('[name=unit_id]').html(options)
				})
			})

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'book.words/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'book.words/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'book.words/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
	    memory: function (){
			const {
				ref,
				computed,
				watch,
				onMounted,
				toRef,
			} = Vue

			Vue.createApp({
				setup(){
					const book = ref(Config.book);
					const allUnitsArr = ref(book.value.unit_list.map((item, index) => index))
					const units = ref(allUnitsArr.value);
					const allUnits = ref(true);
					const sort = ref(0);
					const time = ref(1);
					const words = ref([]);
					const wordIndex = ref(0);
					const hideWord = ref(0);
					const playing = ref(false);
					const timer = ref(null);
					const auto = ref(0);


					const toolbar_hide = ref({'hide': false});
					const toolbar_state = computed(()=> {
						return toolbar_hide.value.hide ? '展开' : '收起'
					});

					const word = computed(()=> {
						let wordTemp = words.value[wordIndex.value];
						return wordTemp != undefined ? wordTemp : {word:'',ipa:'',chinese:''};
					});
					const wordSize = computed(()=> {
						let len = word.value.word.length
						/*if(len < 8){
							return '500px';
						}else if(len < 12 ){
							return '300px';
						}else{
							return '200px';
						}*/
						return '120px';
					});

					// watch([words, wordIndex, time, playing], ()=>{
					// 	createTimer();
					// });

					watch(units, (newVal, oldValue)=>{
						let allUnitsArr = book.value.unit_list.map((item, index) => index)
						allUnits.value = units.value.length == allUnitsArr.length
					})

					onMounted(()=>{
						window.addEventListener('keydown', handleKeydown);
					})

					const handleKeydown = (event)=>{
						switch(event.keyCode){
							// 空格开始暂停
							case 32:
								if(playing.value){
									pause()
								}else{
									play()
								}
								break;
							// 上一个
							case 37:
							case 38:
								prev();
								break;
							// 下一个
							case 40:
								next(true);
								break;
							// 读单词
							case 39:
								handleSpeak(word.value.word);
								break;
						}
				    };
					const getWords = async ()=>{
						const params = {book_id:book.value.id,units:units.value,sort:'id,weigh',order:'asc',offset: 0,limit: 99999}
						await axios.get('book.words/index',{'params':params})
						.then((response) => {
							words.value = response.data.rows;
						})
						.catch((error)=>{
							console.log(error)
						})
					};
					const play = async ()=>{
						if(wordIndex.value == 0){
							await getWords()
							sortWords()
						}
						hideWord.value = 0;
						playing.value = true;
						toolbar_hide.value.hide = true;
						document.documentElement.requestFullscreen();
						createTimer();
					};
					const pause = ()=>{
						playing.value = false;
					};
					const stop = ()=>{
						playing.value = false;
						wordIndex.value = 0;
						words.value = [];
						toolbar_hide.value.hide = false;
						clearTimeout(timer.value);
					};
					const next = (isPause)=>{
						if(wordIndex.value<words.value.length){
							if(isPause === true) pause()
							if(hideWord.value == 1){
								wordIndex.value ++
								hideWord.value = 0
							}else{
								hideWord.value ++;
							}
						}
					};
					const prev = ()=>{
						if(wordIndex.value>0 && words.value.length>0){
							pause()
							if(hideWord.value == -1){
								wordIndex.value --
								hideWord.value = 0
							}else{
								hideWord.value --;
							}
						}
					};
					const createTimer = ()=>{
						clearInterval(timer.value);
						timer.value = setInterval(function(){
							if(playing.value && auto.value==1) next()
						}, time.value * 1000);
					};
					const sortWords = ()=>{
						switch(sort.value){
							case 1:
								return words.value.reverse()
								break;
							case 2:
								return randSort()
								break;
							default:
								return words.value;
								break;
						}
					};
					const randSort = ()=>{
						var wordsTemp = words.value;
						for(var i = 0,len = wordsTemp.length;i < len; i++ ){
							var rand = parseInt(Math.random()*len);
							var temp = wordsTemp[rand];
							wordsTemp[rand] = wordsTemp[i];
							wordsTemp[i] = temp;
						}
						return wordsTemp;
					}
					const handleAllUnits = ()=>{
						let allUnitsArr = book.value.unit_list.map((item, index) => index)
						units.value = allUnits.value ? allUnitsArr : [];
					}

					// 朗读部分
					const detectBrowser = () => {
						const userAgent = navigator.userAgent;
						let browserType = null;
						if(userAgent.indexOf('Edg') > -1 || userAgent.indexOf('Edge') > -1){
							browserType = 'Edge';
						}else if(userAgent.indexOf('Chrome') > -1){
							browserType = 'Chrome';
						}else if(userAgent.indexOf('Safari') > -1){
							browserType = 'Safari';
						}else if(userAgent.indexOf('Firefox') > -1){
							browserType = 'Firefox';
						}else if(userAgent.indexOf('MSIE') > -1 || userAgent.indexOf('Trident/') > -1){
							browserType = 'IE';
						}else{
							browserType = 'unknow';
						}
						return browserType;
					}

					let brower = detectBrowser()
					const synth = window.speechSynthesis // 启用文本
					const msg = new SpeechSynthesisUtterance()

					if(brower == 'Edge') msg.lang = 'en-US' // 使用的语言:中文
					msg.volume = 1 // 声音音量：1
					msg.rate = 1 // 语速：1
					msg.pitch = 1 // 音高：1
					const read = ref(1)

					// 语音播报的函数
					const handleSpeak = (text) => {
						handleStop();
						msg.text = text // 内容
						synth.speak(msg) // 播放
					}
					// 语音停止
					const handleStop = () => {
						synth.cancel() // 取消该次语音播放
					}
					watch(word,(newVal,oldVal)=>{
						if(read.value == 1) handleSpeak(newVal.word)
					})

					return {
						book,
						units,
						allUnits,
						sort,
						time,
						toolbar_hide,
						words,
						wordIndex,
						word,
						wordSize,
						hideWord,
						playing,
						timer,
						toolbar_state,
						auto,
						read,
						play,
						pause,
						stop,
						next,
						prev,
						handleAllUnits,
					}
				},
				template: '#temp',
			}).mount('#app')
	    },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));

				$("#c-book_id").data("eSelect", function(data){

				});
            }
        }
    };
    return Controller;
});
